package com.llb666.shop.payment.infrastructure.persistence;

import com.llb666.common.core.enums.PaymentStatus;
import com.llb666.shop.payment.domain.entity.PayOrders;
import com.llb666.shop.payment.domain.repository.PaymentOrderRepository;
import com.llb666.shop.payment.infrastructure.conver.PayOrdersCvt;
import com.llb666.shop.payment.infrastructure.mapper.PayOrdersMapper;
import com.llb666.shop.payment.infrastructure.po.PayOrdersPo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

/**
 * 支付仓储层实现类.
 *
 * @author llb666
 */
@Repository
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class PaymentOrderRepositoryImpl implements PaymentOrderRepository {

    private final PayOrdersMapper payOrdersMapper;

    @Override
    public void updateOrderPaid(String merchantOrderId, Integer paidAmount) {
        Example example = new Example(PayOrdersPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantOrderId", merchantOrderId);

        PayOrdersPo paidOrder = new PayOrdersPo();
        paidOrder.setPayStatus(PaymentStatus.PAID.type);
        paidOrder.setAmount(paidAmount);
        payOrdersMapper.updateByExampleSelective(paidOrder, example);
    }

    @Override
    public PayOrders queryMerchantPayOrder(String merchantOrderId) {
        Example example = new Example(PayOrdersPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantOrderId", merchantOrderId);
        return PayOrdersCvt.INSTANCE.po2do(payOrdersMapper.selectOneByExample(example));
    }

    @Override
    public PayOrders queryOrderInfo(String merchantUserId, String merchantOrderId) {
        Example example = new Example(PayOrdersPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantOrderId", merchantOrderId);
        criteria.andEqualTo("merchantUserId", merchantUserId);
        return PayOrdersCvt.INSTANCE.po2do(payOrdersMapper.selectOneByExample(example));
    }

    @Override
    public PayOrders queryOrderByStatus(String merchantUserId, String merchantOrderId, Integer type) {
        Example example = new Example(PayOrdersPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantOrderId", merchantOrderId);
        criteria.andEqualTo("merchantUserId", merchantUserId);
        criteria.andEqualTo("payStatus", type);
        return PayOrdersCvt.INSTANCE.po2do(payOrdersMapper.selectOneByExample(example));
    }

    @Override
    public int insert(PayOrders paymentOrder) {
        return payOrdersMapper.insert(PayOrdersCvt.INSTANCE.do2po(paymentOrder));
    }

}
